package com.rhb.rhbaiagent.agent;

import cn.hutool.core.util.StrUtil;
import com.rhb.rhbaiagent.agent.model.AgentState;
import jdk.dynalink.linker.LinkerServices;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 抽象基础代理，用于管理代理状态和执行流程
 * <p>
 * 提供状态转换，内存管理和基于步骤的执行循环的基础功能
 * 子类必须实现step方法
 */
@Data
@Slf4j
public abstract class BaseAgent {
    private String name;

    //提示词
    private String systemPrompt;
    private String nextStepPrompt;

    //代理状态
    private AgentState state = AgentState.IDLE;

    //执行步骤的控制
    private int currentStep;
    private int maxSteps;

    //LLM大模型
    private ChatClient chatClient;

    //Memory记忆，自主维护
    private List<Message> messageList = new ArrayList<>();

    /**
     * 运行代理
     *
     * @param userPrompt 用户提示器
     * @return 执行结果
     */
    public String run(String userPrompt) {
        // 1、基础校验
        if (this.state != AgentState.IDLE) {
            throw new RuntimeException("Cannot run agent from state: " + this.state);
        }
        if (StrUtil.isBlank(userPrompt)) {
            throw new RuntimeException("Cannot run agent with empty user prompt");
        }

        // 2、更改执行状态
        this.state = AgentState.RUNNING;

        // 3、记录消息的上下文
        messageList.add(new UserMessage(userPrompt));

        // 保存结果列表
        List<String> results = new ArrayList<>();

        try {
            for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                int stepNumber = i + 1;
                currentStep = stepNumber;
                log.info("Executing step {}/{}", stepNumber, maxSteps);
                //单步执行
                String stepResult = step();
                String result = "Step" + stepNumber + ": " + stepResult;
                results.add(result);
            }
            if (currentStep >= maxSteps) {
                state = AgentState.FINISHED;
                results.add("Terminated： Reached max steps (" + maxSteps + ")");
            }
            return String.join("\n", results);
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("error executing agent", e);
            return "执行错误" + e.getMessage();
        } finally {
            this.cleanup();
        }
    }

    /**
     * 定义单个步骤怎么进行执行
     *
     * @return 执行结果
     */
    public abstract String step();

    protected void cleanup() {
        //主要用于清理资源
    }

    public SseEmitter runStream(String userPrompt) {
        SseEmitter emitter = new SseEmitter(300000L);
        CompletableFuture.runAsync(() -> {
            try {
                // 1、基础校验
                if (this.state != AgentState.IDLE) {
                    emitter.send("错误：无法从状态运行代理： " + this.state);
                    emitter.complete();
                    return;
                }
                if (StrUtil.isBlank(userPrompt)) {
                    emitter.send("错误：不能使用空提示词进行代理： " + this.state);
                    emitter.complete();
                    return;
                }
                this.state = AgentState.RUNNING;

                // 3、记录消息的上下文
                messageList.add(new UserMessage(userPrompt));

                // 保存结果列表
                List<String> results = new ArrayList<>();

                try {
                    for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                        int stepNumber = i + 1;
                        currentStep = stepNumber;
                        log.info("Executing step {}/{}", stepNumber, maxSteps);
                        //单步执行
                        String stepResult = step();
                        String result = "Step" + stepNumber + ": " + stepResult;
                        emitter.send(result);
                    }
                    if (currentStep >= maxSteps) {
                        state = AgentState.FINISHED;
                        emitter.send("Terminated： Reached max steps (" + maxSteps + ")");
                    }
                    emitter.complete();
                } catch (Exception e) {
                    state = AgentState.ERROR;
                    log.error("error executing agent", e);
                } finally {
                    this.cleanup();
                }
            }catch (Exception e){
                emitter.completeWithError(e);
            }
        });

        emitter.onTimeout(() -> {
            this.state = AgentState.ERROR;
            this.cleanup();
            log.warn("SSE connection timed out");
        });
        emitter.onCompletion(() ->{
            if(this.state == AgentState.RUNNING){
                this.state = AgentState.FINISHED;
            }
            this.cleanup();
            log.info("SSE connection completed");
        });

        return emitter;
    }


}
